package com.cdfy.jwt;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.cdfy.bean.TokenBean;
import com.cdfy.bean.UserBean;

import java.util.Calendar;
import java.util.Date;

/**
 * Jwt工具类
 */
public class JwtUtils {

    //token 有效期为30分 超过则失效
    private static final int minutes = 30;

    /**
     * 获取token
     * @param userBean
     * @return
     */
    public static TokenBean getToken(UserBean userBean) {
        Date expDate = getExpDate();
        String token = JWT.create()
                .withAudience(userBean.getId())
                .withExpiresAt(expDate)
                .sign(Algorithm.HMAC256(userBean.getPassword()));
        TokenBean tokenBean = new TokenBean();
        tokenBean.setToken(token);
        tokenBean.setExpDate(expDate.getTime());
        return tokenBean;
    }

    /**
     * token失效期
     * @return
     */
    public static Date getExpDate() {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE, minutes);
        return calendar.getTime();
    }
}
